<?php if(!defined('WDK_PATH')) exit('No direct script access allowed');
abstract class WdkClass implements ArrayAccess
{	
	function __construct()
	{
		
	}
	
	//--------------------------------------------------------------------------------------------//
	//	functions to implemet for ArrayAccess
	//--------------------------------------------------------------------------------------------//
	public final function offsetSet($offset, $value) {$this->{$offset} = $value;}
    public final function offsetExists($offset) {return isset($this->{$offset});}
    public final function offsetUnset($offset) {unset($this->{$offset});}
    public final function offsetGet($offset) {return isset($this->{$offset}) ? $this->{$offset} : null;}
	//--------------------------------------------------------------------------------------------//

	public function __init($data)
	{
		if(!$data) return;
		$this->backup_data = array();
		foreach($data as $k=>$v)
		{
			if( property_exists($this, $k) )
			{
				$this->{$k} = $v;
				$this->backup_data[$k] = $v;
			}
		}
	}
	protected function isUpdatable()
	{
		foreach($this->backup_data as $k=>$v)
		{
			if($v != $this->{$k}) return true;
		}
		return false;
	}
	public function autoUpdate($log='')
	{
		throw new MethodNotImplementedException("To use autoUpdate, you need to implement first!");
	}
	protected function timeString($time)
	{
		return date('Y-m-d', $time) == date('Y-m-d') ? date('H:i:s', $time) : date('Y-m-d', $time);
	}
	protected function ipString($ip)
	{
		$ip = explode(".", $ip);
		if(count($ip) == 4)
		{
			$ip[0] = str_pad("", strlen($ip[0]), "*", STR_PAD_LEFT);
			$ip[2] = str_pad("", strlen($ip[2]), "*", STR_PAD_LEFT);
			return implode(".", $ip);			
		}
		return $ip;
	}
	
	protected function setBackupData($fields=array())
	{
		$tmp = array(	'origin'=>array(),
						'change'=>array()
		);
		if($fields) // insert/ update
		{
			foreach($fields as $k)
			{
				if(isset($this->backup_data[$k]))
				{
					if($this->backup_data[$k] != $this->{$k}) 
					{
						$tmp['origin'][$k] = $this->backup_data[$k];
						$tmp['change'][$k] = $this->{$k};
					}
				}
				else 
				{
					$tmp['change'][$k] = $this->{$k};
				}
			}
			$this->backup_data = $tmp;
		}
		else // delete 
		{
			$tmp['origin'] = $this->backup_data;
			$this->backup_data = $tmp; 
		}
	}
}